import os
import logging
import time
from logging.handlers import RotatingFileHandler, NTEventLogHandler

from cn.wubo.util.Util import make_dir
from config import BASE_DIR

LOG_PATH = os.path.join(BASE_DIR, 'logs')
LOG_PATH_INFO = os.path.join(LOG_PATH, 'info')
LOG_PATH_WARN = os.path.join(LOG_PATH, 'warn')
LOG_PATH_ERROR = os.path.join(LOG_PATH, 'error')
ENCODE = 'GBK'


# ENCODE = 'UTF-8'


def init_app_log(app):
    logging.basicConfig(level=logging.INFO)

    make_dir(LOG_PATH)
    # Formatter
    formatter = logging.Formatter(
        '%(asctime)s %(levelname)s %(process)d %(thread)d '
        '%(pathname)s %(lineno)s %(message)s')

    suffix_log_file_name = '-' + time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log'

    # FileHandler Info
    file_handler_info = RotatingFileHandler(filename=LOG_PATH_INFO + suffix_log_file_name, encoding=ENCODE)
    file_handler_info.setFormatter(formatter)
    file_handler_info.setLevel(logging.INFO)
    app.logger.addHandler(file_handler_info)

    # FileHandler Error
    file_handler_warn = RotatingFileHandler(filename=LOG_PATH_WARN + suffix_log_file_name, encoding=ENCODE)
    file_handler_warn.setFormatter(formatter)
    file_handler_warn.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler_warn)

    # FileHandler Error
    file_handler_error = RotatingFileHandler(filename=LOG_PATH_ERROR + suffix_log_file_name, encoding=ENCODE)
    file_handler_error.setFormatter(formatter)
    file_handler_error.setLevel(logging.ERROR)
    app.logger.addHandler(file_handler_error)
